﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using FlickrXplorer.Web.Objects;
using System.Collections.Generic;
using FlickrXplorer.Web.Plugin;

namespace MyFlickrXplorerPlugins
{
  public class TagsForThisUser : FlickrXplorerPlugin
  {
    public TagsForThisUser()
      : base("Tags for This User")
    {
      this.LoadSideBar += new EventHandler<LoadSidebarEventArgs>(TagsForThisUser_LoadSideBar);
    }

    private void TagsForThisUser_LoadSideBar(object sender, LoadSidebarEventArgs e)
    {
      // Get the list of tags
      List<string> tags = new List<string>();

      //// DEMO 4 - breakpoint
      /// /// Mehfuz : no need to do Detail everytime for tags,
      /// // extras options will have it already populated.
      foreach (Photo photo in e.PhotoData.Photos.Take(5))
      {
          tags.AddRange(photo.Tags);
      }

      // Count up the number of times each tag appears
      List<TagInfo> tagInfoList = new List<TagInfo>();
      tags.ForEach((string tag) => 
        {
          TagInfo tagInfo = tagInfoList.Where(p => p.Tag.Equals(tag, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
          if(tagInfo == null)
          {
            tagInfo = new TagInfo() 
            {
              HitCount = 1,
              Tag = tag
            };
            tagInfoList.Add(tagInfo);
          }
          else
          {
            tagInfo.HitCount += 1;
          }
        });

      // Display a list showing the top five tags for this user
      StringBuilder builder = new StringBuilder();
      var topFiveTags =
        from t in tagInfoList
        orderby t.HitCount descending
        select t;

      People people = this.PhotoModel.GetPeople(
        this.PhotoModel.GetPhoto(e.PhotoData.Photos[0].Id).Username);

      builder.AppendFormat("<h3>Top tags for {0}</h3>", people.Username);
      builder.Append("<ul>");
      foreach (TagInfo tag in topFiveTags.Take(5).ToArray())
      {
        builder.AppendFormat("<li><a href='/Photo/Tags/{0}' title='{0}'>{0}</a> ({1} hit{2})</li>",
          tag.Tag,
          tag.HitCount,
          (tag.HitCount > 1 ? "s" : ""));
      }
      builder.Append("</ul>");

      e.Content = builder.ToString();
    }

    private class TagInfo
    {
      public string Tag { get; set; }
      public int HitCount { get; set; }
    }
  }
}
